package nl.sportan.samenloop.communication;

import java.util.ArrayList;

import nl.sportan.samenloop.model.ProgramItem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ProgramReader implements Runnable {

	private String url;
	private Result<ArrayList<ProgramItem>> resultHandler = null;

	public ProgramReader(String url) {
		this.url = url;
	}

	
	public void setResultHandler(Result<ArrayList<ProgramItem>> resultHandler) {
		this.resultHandler = resultHandler;
	}
	
	private ArrayList<ProgramItem> getProgram(String jsonData) throws JSONException{
		ArrayList<ProgramItem> items = new ArrayList<ProgramItem>();
		JSONObject obj = new JSONObject(jsonData);
		
		JSONArray arr =	obj.getJSONArray("program");
		for (int i = 0; i < arr.length(); i++) {
			JSONObject itemObject = arr.getJSONObject(i);
			items.add(new ProgramItem(itemObject));
		}
		
		return items;
	}

	public void run() {
		try {
			String jsonData = Utils.retrieveData(this.url);
			ArrayList<ProgramItem> program = getProgram(jsonData);
			if (resultHandler != null) {
				resultHandler.onSucces(program);
			}
			
		} catch (JSONException e) {
			if (resultHandler != null) {
				resultHandler.onFailure(e);
			}
		}
		
	}
	

}
